package com.ztomorrow.ying_cun_plus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.ztomorrow.ying_cun_plus.dao.mapper.NewsContentMapper;
import com.ztomorrow.ying_cun_plus.dao.mapper.NewsInfoMapper;
import com.ztomorrow.ying_cun_plus.dao.po.NewsContent;
import com.ztomorrow.ying_cun_plus.dao.po.NewsInfo;
import com.ztomorrow.ying_cun_plus.dto.resp.NewsInfoRespDto;
import com.ztomorrow.ying_cun_plus.dto.resp.RestResp;
import com.ztomorrow.ying_cun_plus.service.NewsService;
import com.ztomorrow.ying_cun_plus.utils.CacheUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.ztomorrow.ying_cun_plus.constant.front.CacheConstant.*;

@Service
@RequiredArgsConstructor
public class NewsServiceImpl implements NewsService {

    private final CacheUtils cacheUtils;
    private final NewsInfoMapper newsInfoMapper;
    private final NewsContentMapper newsContentMapper;

    @Override
    public RestResp<List<NewsInfoRespDto>> listLatestNews() {
        List<NewsInfoRespDto> cache = cacheUtils.getCache(
                obj -> BeanUtil.copyProperties(obj, NewsInfoRespDto.class),
                CAFFEINE_LATEST_NEWS, REDIS_LATEST_NEWS,
                jsonStr -> JSONUtil.toBean(jsonStr, NewsInfoRespDto.class));
        if (cache != null) return RestResp.ok(cache);
        // 从新闻信息表中查询出最新发布的两条新闻
        List<NewsInfo> list = new LambdaQueryChainWrapper<NewsInfo>(newsInfoMapper)
                .orderByDesc(NewsInfo::getCreateTime)
                .last("limit 2")
                .list();
        List<NewsInfoRespDto> newsInfoRespDto = BeanUtil.copyToList(list, NewsInfoRespDto.class);
        cacheUtils.saveCache( newsInfoRespDto,
                CAFFEINE_LATEST_NEWS, REDIS_LATEST_NEWS, REDIS_LATEST_NEWS_TTL,
                JSONUtil::toJsonStr);
        return RestResp.ok(newsInfoRespDto);
    }

    @Override
    public RestResp<NewsInfoRespDto> getNews(Long id) {
        NewsInfo newsInfo = newsInfoMapper.selectById(id);
        LambdaQueryWrapper<NewsContent> queryWrapper = new LambdaQueryWrapper<NewsContent>()
                .eq(NewsContent::getId, id)
                .last("limit 1");
        NewsContent newsContent = newsContentMapper.selectOne(queryWrapper);
        return RestResp.ok(NewsInfoRespDto.builder()
                .title(newsInfo.getTitle())
                .sourceName(newsInfo.getSourceName())
                .updateTime(newsInfo.getUpdateTime())
                .content(newsContent.getContent())
                .build());
    }
}
